import { useUserStore } from '@/pinia/modules/user'
import { useRouterStore } from '@/pinia/modules/router'
import router from '@/router'
import NProgress from 'nprogress'

const whiteList = ['Login','demo']
// 添加路由
const getRouter = async userStore => {
  const routerStore = useRouterStore()
  await routerStore.SetAsyncRouter()
  routerStore.asyncRouters.allRoutes.forEach(asyncRouter => {
    router.addRoute(asyncRouter)
  })
}

// 格式化缓存组件
async function handleKeepAlive(to) {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1]
        if (element.name === 'layout') {
          to.matched.splice(i, 1)
          await handleKeepAlive(to)
        }
        // 如果没有按需加载完成则等待加载
        if (typeof element.components.default === 'function') {
          await element.components.default()
          await handleKeepAlive(to)
        }
      }
    }
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userStore = useUserStore()
  to.meta.matched = [...to.matched]
  handleKeepAlive(to)
  const token = userStore.token
  const userInfo = userStore.userInfo
  if (token) {
    if (whiteList.indexOf(to.name) != -1) {
      next()
      NProgress.done()
    } else {
      const routerStore = useRouterStore()
      const routes = JSON.parse(JSON.stringify(routerStore.asyncRouters.leftRoutes))
      // 判断是否存储用户信息
      if (userInfo.realName) {
        // 判断是否存储后台路由
        if (routes && routes.length > 0 && routes[0].children && routes[0].children.length > 0) {
          next()
        } else {
          // 添加路由
          await getRouter(userStore)
          next({
            ...to,
            replace: true
          })
        }
      } else {
        // 清除
        userStore.ClearStorage()
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.name) != -1) {
      next()
      Nprogress.done()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 路由加载完成后关闭进度条
  NProgress.done()
})

router.onError(() => {
  // 路由发生错误后销毁进度条
  NProgress.remove()
})
